package com.mall.common.controller;

import java.net.HttpURLConnection;
import java.net.ProtocolException;
import java.net.URL;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import com.mall.common.util.*;
import net.sf.ehcache.Element;

import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.cache.ehcache.EhCacheCacheManager;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

@Controller
@RequestMapping("/admin/system/monitor/ehcache")
public class EhcacheController extends BaseController {
	
	@Resource private EhCacheCacheManager cacheManager;
	
	@RequestMapping
	public String index(Model model) {
		model.addAttribute("cacheManager", cacheManager.getCacheManager());
		return "/admin/system/ehcache/index";
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	@RequestMapping(value="{cacheName}/details", method=RequestMethod.GET)
	public String details(
			@PathVariable("cacheName") String cacheName,
			@RequestParam(value = "searchText", required = false, defaultValue = "") String searchText,
			Model model) {

		model.addAttribute("cacheName", cacheName);
		List allKeys = CacheUtils.getEhcache(cacheName).getKeys();

		List showKeys = Lists.newArrayList();

		for (Object key : allKeys) {
			if (key.toString().contains(searchText)) {
				showKeys.add(key);
			}
		}

		model.addAttribute("keys", showKeys);

		return "/admin/system/ehcache/details";
	}

	@RequestMapping(value="{cacheName}/details", method=RequestMethod.POST)
	@ResponseBody
	public Object keyDetail(@PathVariable("cacheName") String cacheName, String key, Model model) {
		Element element = CacheUtils.getEhcache(cacheName).get(key);
		String dataPattern = "yyyy-MM-dd hh:mm:ss";
		Map<String, Object> data = Maps.newHashMap();
		data.put("objectValue", JsonUtil.getInstance().obj2json(element.getObjectValue()));
		data.put("size",
				PrettyMemoryUtils.prettyByteSize(element.getSerializedSize()));
		data.put("hitCount", element.getHitCount());
		Date latestOfCreationAndUpdateTime = new Date(
				element.getLatestOfCreationAndUpdateTime());
		data.put("latestOfCreationAndUpdateTime", DateFormatUtils.format(
				latestOfCreationAndUpdateTime, dataPattern));
		Date lastAccessTime = new Date(element.getLastAccessTime());
		data.put("lastAccessTime",
				DateFormatUtils.format(lastAccessTime, dataPattern));
		if (element.getExpirationTime() == Long.MAX_VALUE) {
			data.put("expirationTime", "不过期");
		} else {
			Date expirationTime = new Date(element.getExpirationTime());
			data.put("expirationTime",
					DateFormatUtils.format(expirationTime, dataPattern));
		}
		data.put("timeToIdle", element.getTimeToIdle());
		data.put("timeToLive", element.getTimeToLive());
		data.put("version", element.getVersion());
		return data;
	}

	@RequestMapping(value="{cacheName}/delete",method=RequestMethod.POST)
	public String delete(@PathVariable("cacheName") String cacheName, String key, HttpServletResponse response) {
		CacheUtils.cleanEhCache(cacheName, key);;
		return ResponseUtils.renderJSON(successMessage, response);
	}

	@RequestMapping("{cacheName}/clear")
	@ResponseBody
	public Object clear(@PathVariable("cacheName") String cacheName,
			HttpServletResponse response) {
		CacheUtils.clearCache(cacheName);
		try {
			URL url = new URL("http://www.360kuajie.com/cleanPageCache.jhtml");
			HttpURLConnection htpcon = (HttpURLConnection) url.openConnection();
			htpcon.setRequestMethod("GET");
			htpcon.setDoOutput(true);
			htpcon.setDoInput(true);
			htpcon.setUseCaches(false);
		} catch (Exception e) { }
		return ResponseUtils.renderJSON(successMessage, response);
	}

}